package edu.mju.admin.controller;


import edu.mju.admin.entity.SysPermission;
import edu.mju.admin.service.SysPermissionService;
import edu.mju.serviceutils.ResponseCode;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 权限 前端控制器
 * </p>
 *
 * @author CBL
 * @since 2021-01-10
 */
@RestController
@RequestMapping("/admin/sys-permission")
public class SysPermissionController {

    @Autowired
    private SysPermissionService permissionService;


    /**
     * 获取全部菜单
     *
     * @return json格式
     */
    @ApiOperation(value = "查询所有菜单")
    @GetMapping
    public ResponseCode indexAllPermission() {
        List<SysPermission> list = permissionService.queryAllMenu();
        Map<String, Object> map = new HashMap<>();
        map.put("children", list);
        return ResponseCode.success().data(map);
    }

    @ApiOperation(value = "递归删除菜单")
    @DeleteMapping("/remove/{id}")
    public ResponseCode remove(@PathVariable Integer id) {
        permissionService.removeChildById(id);
        return ResponseCode.success();
    }

    @ApiOperation(value = "给角色分配权限")
    @PostMapping("/doAssign")
    public ResponseCode doAssign(Integer roleId, Integer[] permissionId) {
        permissionService.saveRolePermission(roleId, permissionId);
        return ResponseCode.success();
    }

    @ApiOperation(value = "根据角色获取菜单")
    @GetMapping("/toAssign/{roleId}")
    public ResponseCode toAssign(@PathVariable Integer roleId) {
        List<SysPermission> list = permissionService.selectAllMenu(roleId);
        Map<String, Object> map = new HashMap<>();
        map.put("children", list);
        return ResponseCode.success().data(map);
    }


    @ApiOperation(value = "新增菜单")
    @PostMapping("/save")
    public ResponseCode save(@RequestBody SysPermission permission) {
        permissionService.save(permission);
        return ResponseCode.success();
    }

    @ApiOperation(value = "修改菜单")
    @PutMapping("/update")
    public ResponseCode updateById(@RequestBody SysPermission permission) {
        permissionService.updateById(permission);
        return ResponseCode.success();
    }
}

